package com.srwl.mytx.activity;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.LiveRoomListAdapter;
import com.srwl.mytx.adapter.SearchHistoryAdapter;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.SearchDataItem;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.PreferenceManager;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.SearchView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LiveRoomSearchActivity extends BaseActivity {

    private static final String TAG = "LiveRoomSearchActivity";
    private SearchView searchView;  //搜索框对象
    private RecyclerView rv_searchResult;
    private RecyclerView rv_searchData;
    private SearchHistoryAdapter searchHistoryAdapter;
    private LiveRoomListAdapter liveRoomListAdapter;
    private ProgressBar progressBar;
    private View searchResultEmpty;
    private List<LiveRoom> searchResultList = new ArrayList<>();    //搜索结果的数据源
    private List<String> searchHistoryList = new ArrayList<>();     //历史搜索记录的数据集合
    private List<String> searchHotspotList = new ArrayList<>();     //热门搜索数据集合
    private List<SearchDataItem> searchSumList = new ArrayList<>();  //搜索数据的数据源
    private String hintString;  //搜索输入框的提示内容

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_live_room);
        //获取引用
        rv_searchData = findViewById(R.id.rv_search_live_room_history);
        rv_searchResult = findViewById(R.id.rv_search_live_room_result);
        progressBar = findViewById(R.id.progress_bar);
        searchResultEmpty = findViewById(R.id.search_result_empty);
        initSearchHistoryRecyclerView();
        findHotspotDataLiveRoom();
        initSearchResultRecyclerView();
        initSearchView();
    }

    private void initSearchHistoryRecyclerView() {
        //获取SharedPreference中存储的搜索历史记录将其加入到历史记录的数据源中,并实现其适配器中的几个回调接口，处理其item的几种点击事件
        List<String> currentUserSearchHistory = PreferenceManager.getInstance().getCurrentUserSearchHistoryLiveRoom();
        if (currentUserSearchHistory != null) {
            searchHistoryList.addAll(currentUserSearchHistory);
            Log.d(TAG, "initSearchHistoryRecyclerView: 本地储存的历史搜索记录为：" + currentUserSearchHistory);
        } else {
            Log.d(TAG, "initSearchHistoryRecyclerView: 本地储存的历史搜索记录为空");
        }

        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 840);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            //加载每个item时回调该方法，用于获取其展示的宽度
            @Override
            public int getSpanSize(int position) {
                int searchDataLength = searchSumList.get(position).getContent().length();
                if (searchSumList.get(position).getType() == SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HISTORY
                        || searchSumList.get(position).getType() == SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HOTSPOT) {
                    return 840;
                } else if (searchDataLength == 1) {
                    return 840 / 8;
                } else if (searchDataLength == 2) {
                    return 840 / 6;
                } else if (searchDataLength == 3) {
                    return 840 / 4;
                } else if (searchDataLength == 4) {
                    return 840 / 4;
                } else if (searchDataLength == 5) {
                    return 840 / 3;
                } else if (searchDataLength == 6) {
                    return 840 / 3;
                } else if (searchDataLength == 7) {
                    return 840 / 2;
                } else if (searchDataLength >= 8) {
                    return 840 / 2;
                }
                return 0;
            }
        });
        rv_searchData.setLayoutManager(gridLayoutManager);
        searchHistoryAdapter = new SearchHistoryAdapter(this, searchSumList);
        rv_searchData.setAdapter(searchHistoryAdapter);

        searchHistoryAdapter.setSearchHistoryClearAll(new SearchHistoryAdapter.SearchHistoryClearAll() {
            //点击清除所有搜索历史的图标后回调的具体执行逻辑
            @Override
            public void clearAll(int position) {
                ConfirmDialog dialog = new ConfirmDialog(LiveRoomSearchActivity.this, "提醒", "确定清除最近历史记录？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        int size = searchHistoryList.size();
                        searchHistoryList.clear();
                        PreferenceManager.getInstance().setCurrentUserSearchHistoryLiveRoom(searchHistoryList);
                        for (int i = 0; i <= size; i++) {
                            searchSumList.remove(0);
                            searchHistoryAdapter.notifyDataSetChanged();
                        }
                    }
                });
                dialog.show();
            }
        });

        searchHistoryAdapter.setSearchHistoryItemClickListener(new SearchHistoryAdapter.SearchHistoryItemClickListener() {
            @Override
            public void onItemClick(int position) {
                //单击搜索历史记录item的回调执行逻辑
                String content = searchSumList.get(position).getContent();
                searchView.et_content.setText(content);
                search(content, null);
            }

            @Override
            public void onItemLongClick(int position) {
                //长按搜索历史记录item的回调执行逻辑
                ConfirmDialog dialog = new ConfirmDialog(LiveRoomSearchActivity.this, "提醒", "确定删除吗？", true);
                dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                    @Override
                    public void confirm() {
                        String content = searchSumList.get(position).getContent();
                        searchHistoryList.remove(content);
                        PreferenceManager.getInstance().setCurrentUserSearchHistoryLiveRoom(searchHistoryList);
                        if (searchHistoryList.size() == 0) {
                            //清除对应数据和"最近搜索:"标题栏
                            searchSumList.remove(position);
                            searchSumList.remove(0);
                        } else {
                            searchSumList.remove(position);
                        }
                        searchHistoryAdapter.notifyDataSetChanged();
                    }
                });
                dialog.show();

            }
        });
    }

    private void findHotspotDataLiveRoom() {
        //从服务端获取热搜数据，并初始化搜索数据源
        RetrofitManager.getInstance()
                .createRequest(TopicService.class)
                .hotspotData()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult commonResult = response.body();
                        if (!response.isSuccessful() || commonResult == null) {
                            Log.e(TAG, "onResponse: 响应失败！" + response.message());
                            return;
                        }
                        if (commonResult.isError()) {
                            Log.e(TAG, "onResponse: 响应错误！" + commonResult.getMsg());
                            return;
                        }
                        Log.d(TAG, "onResponse: 响应回来的数据:" + commonResult);

                        //解析响应数据,并添加到热搜数据集中
                        JSONArray jsonArray = (JSONArray) commonResult.getData();
                        searchHotspotList.addAll(jsonArray.toJavaList(String.class));

                        //给搜索数据源绑定数据
                        if (searchHistoryList.size() != 0) {
                            searchSumList.add(new SearchDataItem("最近搜索:", SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HISTORY));
                            for (String searchHistory : searchHistoryList) {
                                searchSumList.add(new SearchDataItem(searchHistory, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_LOCAL_CONTENT));
                            }
                        }
                        if (searchHotspotList.size() != 0) {
                            searchSumList.add(new SearchDataItem("热门搜索:", SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HOTSPOT));
                            for (String searchHotspot : searchHotspotList) {
                                searchSumList.add(new SearchDataItem(searchHotspot, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_REMOTE_CONTENT));
                            }
                        }
                        //通知适配器数据源改变
                        searchHistoryAdapter.notifyDataSetChanged();

                        if (searchHotspotList.size() != 0) {
                            //从热搜数据集合中随机获取一条设置为输入框的Hint
                            int randomIndex = (int) (Math.random() * (searchHotspotList.size() - 1));
                            hintString = searchHotspotList.get(randomIndex);
                            searchView.et_content.setHint(hintString);
                        }
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        t.printStackTrace();
                    }
                });

    }

    private void initSearchResultRecyclerView() {
        liveRoomListAdapter = new LiveRoomListAdapter(this, searchResultList);
        rv_searchResult.setLayoutManager(new GridLayoutManager(this, 2));
        rv_searchResult.setAdapter(liveRoomListAdapter);
    }


    private void initSearchView() {
        //实现搜索框对象(SearchView)的回调接口,获取其搜索框的输入内容，并将其添加进历史搜索记录
        searchView = findViewById(R.id.search_view);
        searchView.setListener(new SearchView.InteractionListener() {
            //当点击搜索按钮后回调
            @Override
            public void onSearch(String content) {
                //判断其搜索框中的内容是否为空
                if (TextUtils.isEmpty(content)) {
                    //为空则将Hint数据设置为搜索内容
                    content = hintString;
                    searchView.et_content.setText(content);
                }
                //搜索数据
                search(content, null);

                //判断搜索历史记录是否为0
                if (searchHistoryList.size() == 0) {
                    searchSumList.add(0, new SearchDataItem("最近搜索:", SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_TITLE_SEARCH_HISTORY));
                }

                //将搜索数据添加进搜索历史记录中。判断搜索内容是否已经存在搜索历史中
                if (searchHistoryList.contains(content)) {
                    //存在搜索历史中，删除其已经存在的数据，并将该数据重新加载到搜索历史的第一个位置
                    int index = searchHistoryList.indexOf(content); //先获取重复数据的索引
                    searchHistoryList.remove(content);
                    searchHistoryList.add(0, content);
                    //更新搜索记录适配器中的数据源
                    searchSumList.remove(index + 1);
                    searchSumList.add(1, new SearchDataItem(content, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_LOCAL_CONTENT));
                } else {
                    //搜索历史中不存在,直接添加到搜索历史记录的首位
                    searchHistoryList.add(0, content);
                    //更新搜索记录适配器中的数据源
                    searchSumList.add(1, new SearchDataItem(content, SearchDataItem.SEARCH_HISTORY_ITEM_TYPE_LOCAL_CONTENT));
                }

                //使搜索历史记录只显示最近10条
                if (searchHistoryList.size() == 11) {
                    //当等于11条时，删除最后一条，使其只保持10条搜索历史
                    searchHistoryList.remove(10);
                    searchSumList.remove(11);
                }

                //更新本地存储的搜索历史记录数据
                PreferenceManager.getInstance().setCurrentUserSearchHistoryLiveRoom(searchHistoryList);
                //通知适配器数据源改变
                searchHistoryAdapter.notifyDataSetChanged();

            }

            //输入框内容改变时回调
            @Override
            public void onTextChange(String content) {
                //当输入框内容为空的时候显示搜索数据界面
                if (content.length() == 0) {
                    rv_searchResult.setVisibility(View.GONE);
                    searchResultEmpty.setVisibility(View.GONE);
                    rv_searchData.setVisibility(View.VISIBLE);
                }
            }
        });
    }


    private void search(String query, SearchHistoryAdapter.MyViewHolder viewHolder) {
        hideSoftKeyboard();
        rv_searchData.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
        Map<String, Object> info = new HashMap<>();
        info.put("queryContent", query);
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .searchLiveRoom(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        if (viewHolder != null) {
                            viewHolder.progressBar.setVisibility(View.GONE);
                        } else if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "ES搜索失败：" + response.message());
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "ES搜索失败：" + result.getMsg());
                            return;
                        }
                        rv_searchData.setVisibility(View.GONE);
                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "ES搜索完成" + jsonObject);
                        List<Topic> resultsList = JSONObject.parseArray(jsonObject.getString("hits"), Topic.class);
                        List<Integer> audienceSizeList = JSONObject.parseArray(jsonObject.getString("audienceSizeList"), Integer.class);

                        searchResultList.clear();
                        liveRoomListAdapter.notifyDataSetChanged();
                        if (resultsList == null || resultsList.size() == 0) {
                            if (!searchResultEmpty.isShown()) {
                                searchResultEmpty.setVisibility(View.VISIBLE);
                            }
                            return;
                        }
                        List<LiveRoom> liveRooms = new ArrayList<>();
                        for (int index = 0; index < resultsList.size(); index++) {
                            Topic topic = resultsList.get(index);
                            LiveRoom liveRoom = new LiveRoom();
                            liveRoom.setId(topic.getId());
                            liveRoom.setManagerId(topic.getManagerId());
                            liveRoom.setChatId(topic.getId());
                            liveRoom.setTitle(topic.getTitle());
                            liveRoom.setStatus(topic.getStatus());
                            liveRoom.setVideo(topic.getVideo());
                            liveRoom.setAudienceSize(audienceSizeList.get(index));

                            if (!TextUtils.isEmpty(topic.getVideo())) {//图片和视频，至少有一样存在
                                liveRoom.setCover(topic.getVideoCover());
                            } else if (topic.getPictures() != null && topic.getPictures().size() != 0) {
                                liveRoom.setCover(topic.getPictures().get(0));
                            }
                            liveRooms.add(liveRoom);
//                            agoraAPIOnlySignal.channelQueryUserNum(liveRoom.getId());
                        }
                        searchResultList.addAll(liveRooms);
                        liveRoomListAdapter.notifyDataSetChanged();
                        //搜索完成后，隐藏历史记录的RecyclerView，显示搜索的RecyclerView
                        searchResultEmpty.setVisibility(View.GONE);
                        rv_searchResult.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "ES搜索失败：" + t.getMessage());
                        if (viewHolder != null) {
                            viewHolder.progressBar.setVisibility(View.GONE);
                        } else if (progressBar.isShown()) {
                            progressBar.setVisibility(View.GONE);
                        }

                    }
                });
    }

}
